package com.zff.rental.repository.apartment;

import com.zff.rental.entity.apartment.AttachmentEntity;
import com.zff.rental.mapstruct.apartment.AttachmentMapstruct;
import com.zff.rental.utils.collectors.CollectionsUtils;
import com.zff.rental.vo.apartment.attachment.EditAttachmentVo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HCY
 */
@Repository
public interface AttachmentRepository extends JpaRepository<AttachmentEntity, Long> {
    List<AttachmentEntity> findAllByBelongIdAndBelongType(Long belongId, int belongType);

    /**
     * 保存并删除
     * null 则忽略
     * 空数组则删除
     */
    default List<AttachmentEntity> saveAllOrDelete(List<EditAttachmentVo> srcVoList, Long belongId, Integer belongType) {
        if (srcVoList != null) {
            if (srcVoList.isEmpty()) {
                deleteAllByBelongIdAndBelongType(belongId, belongType);
            } else {
                List<AttachmentEntity> oldList = findAllByBelongIdAndBelongType(belongId, belongType);
                List<AttachmentEntity> newList = AttachmentMapstruct.INSTANCE.map(srcVoList, belongId, belongType);

                List<AttachmentEntity> delList = CollectionsUtils.reduceToList(oldList, newList, AttachmentEntity::getObjectKey);
                List<AttachmentEntity> addList = CollectionsUtils.reduceToList(newList, oldList, AttachmentEntity::getObjectKey);
                List<AttachmentEntity> updateList = CollectionsUtils.intersectionToList(oldList, newList, AttachmentEntity::getObjectKey);

                if (!delList.isEmpty()) {
                    deleteAll(delList);
                }
                if (!addList.isEmpty()) {
                    saveAll(addList);
                }
                if (!updateList.isEmpty()) {
                    // 更新的数据只有序号
                    Map<String, Integer> collect = newList.stream()
                            .collect(Collectors.toMap(AttachmentEntity::getObjectKey, AttachmentEntity::getSerialNumber, (v1, v2) -> v1));
                    for (AttachmentEntity attachmentEntity : updateList) {
                        attachmentEntity.setSerialNumber(collect.get(attachmentEntity.getObjectKey()));
                    }
                    saveAll(updateList);
                }
            }
        }
        List<AttachmentEntity> result = findAllByBelongIdAndBelongType(belongId, belongType);
        result.sort(Comparator.comparingInt(e -> e.getSerialNumber() == null ? Integer.MAX_VALUE : e.getSerialNumber()));
        return result;
    }

    /**
     * 根据所属的ID和类型删除
     */
    void deleteAllByBelongIdAndBelongType(Long belongId, Integer belongType);

    List<AttachmentEntity> findAllByBelongIdInAndBelongType(List<Long> roomIdList, Integer belongType);

    void deleteAllByBelongId(Long belongId);
}
